﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SeDuce.BLL;
using Ajax;
using SeDuce.Model;
using System.Data.SqlClient;
using SeDuce.DAL;
using System.Text;
using System.Data;

public partial class Brands : RepeaterPagerBase
{
    Lazy_Yu<BrandBLL> lazyBrandBLL = new Lazy_Yu<BrandBLL>(() => new BrandBLL());
    public BrandBLL LazyBrandBLL
    {
        get { return this.lazyBrandBLL.Value; }
    }

    Lazy_Yu<TypeBLL> lazyTypeBLL = new Lazy_Yu<TypeBLL>(() => new TypeBLL());
    public TypeBLL LazyTypeBLL
    {
        get { return this.lazyTypeBLL.Value; }
    }

    Lazy_Yu<AdBLL> lazyAdBLL = new Lazy_Yu<AdBLL>(() => new AdBLL());
    public AdBLL LazyAdBLL
    {
        get { return this.lazyAdBLL.Value; }
    }

    Lazy_Yu<ProductBLL> lazyProductBLL = new Lazy_Yu<ProductBLL>(() => new ProductBLL());
    public ProductBLL LazyProductBLL
    {
        get { return this.lazyProductBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(Brands));
        if (!IsPostBack)
        {
            Brand brand = this.LazyBrandBLL.GetBrandByBrandID(this.GetQueryString("brandID", false).ToInt()).ToList<Brand>().SingleOrDefault<Brand>();
            if (brand != null)
            {
                this.imgBrandLogo.ImageUrl = ResolveUrl(brand.BrandImage);
                this.literBrandName.Text = HttpUtility.HtmlEncode(brand.BrandName);
            }

            this.rptNewProducts.DataSource = this.LazyProductBLL.GetProductsTop(15).ToList<SeDuce.Model.Product>().OrderByDescending(p => p.ProductID);
            this.rptNewProducts.DataBind();
        }
        if (ScriptManager1.IsInAsyncPostBack && !ScriptManager1.IsNavigating)
            ScriptManager1.AddHistoryPoint("category", this.GetQueryString("brandID", false), string.Format("Category {0}", this.GetQueryString("brandID", false)));
        BindCategories();
        this.rptTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
        this.rptTypes.DataBind();
        this.rptAds.DataSource = this.LazyAdBLL.GetAds().ToList<Ad>().Where<Ad>(a => a.Enabled == true);
        this.rptAds.DataBind();

        this.BindProducts();

        this.rptPageFliper.ItemCommand += new RepeaterCommandEventHandler(rptPageFliper_ItemCommand);
    }

    protected void rptPageFliper_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (ScriptManager1.IsInAsyncPostBack && !ScriptManager1.IsNavigating)
            ScriptManager1.AddHistoryPoint("brand", e.CommandName, string.Format("Page {0}", e.CommandName));
    }

    protected void ScriptManager1_Navigate(object sender, HistoryEventArgs e)
    {
        if (e.State["brand"] != null)
        {
            this.BindPage(this.rptPageFliper.UniqueID, e.State["brand"].ToString().ToInt());
        }
        //else
        //{
        //    this.BindPage(this.rptPageFliper.UniqueID, 1);
        //}

        if (e.State["category"] != null)
        {
            Brand brand = this.LazyBrandBLL.GetBrandByBrandID(e.State["category"].ToString().ToInt()).ToList<Brand>().SingleOrDefault<Brand>();
            this.imgBrandLogo.ImageUrl = ResolveUrl(brand.BrandImage);
            this.literBrandName.Text = brand.BrandName;
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key1", "javascript:updateCategories()", true);
            this.AddAttributes("Category_Filter", "BrandID=" + e.State["category"].ToString());
            this.AddAttributes("Type_Filter", string.Empty);
            this.BindCategories();
            this.rptTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
            this.rptTypes.DataBind();
            this.BindProducts();
            this.BindPage(this.rptPageFliper.UniqueID, 1);
        }

        if (e.State["types"] != null)
        {
            this.AddAttributes("Type_Filter", e.State["types"]);
            this.lbtnTypeAll.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);
            this.rptTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
            this.rptTypes.DataBind();
            this.BindProducts();
            this.BindPage(this.rptPageFliper.UniqueID, 1);
        }

        if (e.State["category"] != null && e.State["types"] != null)
        {
            Brand brand = this.LazyBrandBLL.GetBrandByBrandID(this.GetQueryString("brandID", false).ToInt()).ToList<Brand>().SingleOrDefault<Brand>();
            this.imgBrandLogo.ImageUrl = ResolveUrl(brand.BrandImage);
            this.literBrandName.Text = brand.BrandName;
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key1", "javascript:updateCategories()", true);
            this.AddAttributes("Category_Filter", "BrandID=" + this.GetQueryString("brandID", false));
            this.AddAttributes("Type_Filter", string.Empty);
            this.BindCategories();
            this.rptTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
            this.rptTypes.DataBind();
            this.BindProducts();
            this.BindPage(this.rptPageFliper.UniqueID, 1);
        }
    }

    private void BindCategories()
    {
        this.rptCategories.DataSource = this.LazyBrandBLL.GetBrands().ToList<Brand>().OrderBy(t => t.Sort).ToList<Brand>();
        this.rptCategories.DataBind();
    }

    [Ajax.AjaxMethod()]
    public bool UpdateBrands()
    {
        try
        {
            BindCategories();
            return true;
        }
        catch { return false; }
    }

    private void BindProducts()
    {
        List<SqlParameter> sp = new List<SqlParameter>();
        string where = string.Empty;
        string whereExists = string.Empty;
        //类别过滤
        if (!string.IsNullOrEmpty(this.GetAttributes("Type_Filter")))
        {
            List<string> typeFilters = this.GetAttributes("Type_Filter").Split(',').ToList<string>();
            for (int i = 0; i < typeFilters.Count; i++)
            {
                string key = typeFilters[i].Split('=')[0];
                string value = typeFilters[i].Split('=')[1];

                if (value == "31" || value == "32")//男装或女装
                {
                    if (string.IsNullOrEmpty(whereExists))
                    {
                        whereExists = " AND EXISTS (SELECT DISTINCT TbProduct_1.ProductID FROM TbBrand AS TbBrand_1 INNER JOIN TbProdcutBrand_Map AS TbProdcutBrand_Map_1 ON TbBrand_1.BrandID = TbProdcutBrand_Map_1.BrandID RIGHT OUTER JOIN TbProductType_Map AS TbProductType_Map_1 INNER JOIN TbType AS TbType_1 ON TbProductType_Map_1.TypeID = TbType_1.TypeID RIGHT OUTER JOIN TbProduct AS TbProduct_1 ON TbProductType_Map_1.ProductID = TbProduct_1.ProductID ON TbProdcutBrand_Map_1.ProductID = TbProduct_1.ProductID WHERE (1 = 1) AND (TbProduct.ProductID = TbProduct_1.ProductID) AND (";
                    }
                    sp.Add(new SqlParameter("@" + key.Split('.')[1] + i, value));
                    whereExists += string.Format("TbProductType_Map_1.TypeID=@{0} OR ", key.Split('.')[1] + i);
                }
                else
                {
                    if (string.IsNullOrEmpty(where))
                    {
                        where += " AND (";
                    }
                    sp.Add(new SqlParameter("@" + key.Split('.')[1] + i, value));
                    where += string.Format("{0}=@{1} OR ", key, key.Split('.')[1] + i);
                }
            }
            if (!string.IsNullOrEmpty(where))
            {
                where = where.TrimEnd("OR ".ToArray()) + ")";
            }
            if (!string.IsNullOrEmpty(whereExists))
            {
                whereExists = whereExists.TrimEnd("OR ".ToArray()) + "))";
            }
        }
        //品牌过滤
        if (!string.IsNullOrEmpty(this.GetAttributes("Category_Filter")))
        {
            string key = this.GetAttributes("Category_Filter").Split('=')[0];
            string value = this.GetAttributes("Category_Filter").Split('=')[1];
            sp.Add(new SqlParameter("@" + key, value));
            where += string.Format(" AND TbBrand.{0}=@{0}", key);
        }
        else
        {
            sp.Add(new SqlParameter("@BrandID", this.GetQueryString("brandID", false)));
            where += string.Format(" AND TbBrand.{0}=@{0}", "BrandID");
        }
        this.RegistrPager(this.rptProducts, this.rptPageFliper, 7, this.FillPageMoudleWithParams(PageSize, SeDuce.DAL.ProductDAL.sqlGetProducts + where + whereExists, sp.ToArray(), new List<SortField>() { 
            new SortField() { FieldName = "Seq", DESC = true },
            new SortField() { FieldName = "Date", DESC = true }
        }));

        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key2", "javascript:$.utility.ellipsis({ selector: '.product .info p a', length: 30 })", true);

        this.txtPageNum.Visible = (this.TotalPage(this.rptPageFliper.UniqueID) > 1);
        this.lbtnGo.Visible = (this.TotalPage(this.rptPageFliper.UniqueID) > 1);
    }

    protected void rptTypes_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "TYPE_CHANGE")
        {
            LinkButton lbtnType = (LinkButton)e.Item.FindControl("lbtnType");
            List<string> typeFilters = this.GetAttributes("Type_Filter").Split(',').ToList<string>();
            if (typeFilters.Contains("TbProductType_Map.TypeID=" + e.CommandArgument.ToString()))
            {
                typeFilters.Remove("TbProductType_Map.TypeID=" + e.CommandArgument.ToString());
                lbtnType.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);
            }
            else
            {
                typeFilters.Add("TbProductType_Map.TypeID=" + e.CommandArgument.ToString());
                lbtnType.ForeColor = System.Drawing.Color.White;
            }
            this.AddAttributes("Type_Filter", string.Join(",", typeFilters.ToArray<string>()).Trim(','));
            this.lbtnTypeAll.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);

            if (ScriptManager1.IsInAsyncPostBack && !ScriptManager1.IsNavigating)
                ScriptManager1.AddHistoryPoint("types", this.GetAttributes("Type_Filter"), string.Format("Types {0}", this.GetAttributes("Type_Filter")));

            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key3", "javascript:updateCategories();", true);

            this.BindProducts();
            this.BindPage(this.rptPageFliper.UniqueID, 1);
        }
    }
    protected void rptCategories_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "CATEGORY_CHANGE")
        {
            if (ScriptManager1.IsInAsyncPostBack && !ScriptManager1.IsNavigating)
                ScriptManager1.AddHistoryPoint("category", e.CommandArgument.ToString(), string.Format("Category {0}", e.CommandArgument));
            LinkButton lbtnCategory = (LinkButton)e.Item.FindControl("lbtnCategory");
            Brand brand = this.LazyBrandBLL.GetBrandByBrandID(e.CommandArgument.ToString().ToInt()).ToList<Brand>().SingleOrDefault<Brand>();
            this.imgBrandLogo.ImageUrl = ResolveUrl(brand.BrandImage);
            this.literBrandName.Text = lbtnCategory.Text;
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key1", "javascript:updateCategories()", true);
            this.AddAttributes("Category_Filter", "BrandID=" + e.CommandArgument.ToString());
            this.AddAttributes("Type_Filter", string.Empty);
            this.lbtnTypeAll.ForeColor = System.Drawing.Color.White;
            BindCategories();
            this.BindProducts();
            this.BindPage(this.rptPageFliper.UniqueID, 1);

        }
    }
    protected string GetProductStatus(int statusID)
    {
        string status = string.Empty;
        switch (statusID)
        {
            case 1:
                status = ResolveUrl("~/images/status_spot.gif");
                break;
            case 2:
                status = ResolveUrl("~/images/status_reservation.gif");
                break;
            case 3:
                status = ResolveUrl("~/images/status_sale.gif");
                break;
            case 4:
                status = ResolveUrl("~/images/status_soldout.gif");
                break;
            default:
                break;
        }
        return status;
    }
    protected void lbtnTypeAll_Click(object sender, EventArgs e)
    {
        this.lbtnTypeAll.ForeColor = System.Drawing.Color.White;
        this.AddAttributes("Type_Filter", string.Empty);
        this.rptTypes.DataSource = this.LazyTypeBLL.GetTypes().ToList<SeDuce.Model.Type>().OrderBy(t => t.Sort);
        this.rptTypes.DataBind();
        this.BindProducts();
        this.BindPage(this.rptPageFliper.UniqueID, 1);
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        int num = 0;
        if (int.TryParse(this.txtPageNum.Text.Trim(), out num))
        {
            if (num <= this.TotalPage(this.rptPageFliper.UniqueID) && num > 0)
            {
                this.BindProducts();
                this.BindPage(this.rptPageFliper.UniqueID, num);
            }
        }
    }
    protected void rptTypes_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LinkButton lbtnType = (LinkButton)e.Item.FindControl("lbtnType");
            List<string> typeFilters = this.GetAttributes("Type_Filter").Split(',').ToList<string>();
            if (typeFilters.Contains("TbProductType_Map.TypeID=" + lbtnType.CommandArgument.ToString()))
            {
                lbtnType.ForeColor = System.Drawing.Color.White;
            }
            else
            {
                lbtnType.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);
            }
        }
    }
    protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LinkButton lbtnCategory = (LinkButton)e.Item.FindControl("lbtnCategory");
            if (!string.IsNullOrEmpty(this.GetAttributes("Category_Filter")))
            {
                string categoryId = this.GetAttributes("Category_Filter").Split('=')[1];
                if (categoryId == lbtnCategory.CommandArgument.ToString())
                {
                    lbtnCategory.ForeColor = System.Drawing.Color.White;
                }
                else
                {
                    lbtnCategory.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);
                }
            }
            else
            {
                string categoryId = this.GetQueryString("brandID", false);
                if (categoryId == lbtnCategory.CommandArgument.ToString())
                {
                    lbtnCategory.ForeColor = System.Drawing.Color.White;
                }
                else
                {
                    lbtnCategory.ForeColor = System.Drawing.Color.FromArgb(120, 120, 120);
                }
            }
        }
    }

    protected string GetTagsXML()
    {
        StringBuilder sb = new StringBuilder("<tags>");
        DataTable dtBrands = LazyBrandBLL.GetBrands();
        for (int i = 0; i < dtBrands.Rows.Count; i++)
        {
            sb.Append(string.Format("<a href='{0}' style='20' color='{2}'>{1}</a>", Utils.GetRootURI() + "/Brands/" + dtBrands.Rows[i]["BrandID"].ToString(), HttpUtility.HtmlEncode(dtBrands.Rows[i]["BrandName"].ToString()), Utils.CreateSpecifiedColor(new List<string>() { "0x97c3ff", "0xff9797", "0x99ff97", "0x97edff", "0xa197ff", "0xff97ed" })));
        }
        sb.Append("<a href='http://weibo.com/seduceyy' style='20' color='0xff0000' target='_blank'>Se'Duce</a>");
        sb.Append("</tags>");
        return sb.ToString();
    }
}